<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\controller;

use plugin\ai\app\event\data\EventData;
use plugin\ai\app\service\Audio;
use plugin\ai\app\service\Category;
use plugin\ai\app\service\Common;
use plugin\ai\app\service\Model;
use plugin\ai\app\service\Plan;
use plugin\ai\app\service\Setting;
use plugin\ai\app\service\User;
use support\Request;
use support\Response;
use Webman\Event\Event;

class SettingController extends Base
{
    /**
     * 不需要登录的方法
     *
     * @var string[]
     */
    protected $noNeedLogin = ['index', 'models', 'categories'];

    /**
     * 获取配置
     *
     * @return Response
     */
    public function index(): Response
    {
        $models = Model::getSetting();
        $enabledModelTypes = Common::getModelTypes();
        $availableModels = Common::getModels();
        foreach ($models as $model => $name) {
            if (!in_array($model, $availableModels)) {
                unset($models[$model]);
            }
        }
        $setting = Setting::getSetting();
        $audioSetting = Audio::getSetting();
        $menus = [
            'painting' => [
                'enabled' => $enabledModelTypes['midjourney'] ?? false, // 是否开启
                'title' => '绘画',
                'icon' => [ // 图标
                    'light' => '<i class="icon-painting"></i>',
                    'dark' => '<i class="icon-painting"></i>',
                    'active' => '<i class="icon-painting-fill"></i>'
                ],
                'url' => '/app/ai/painting', // iframe url
                'mobile' => true, // 移动端显示入口
                'keep' => true, // 切换标签后iframe保留，避免重复加载
            ],
            'market' => [
                'enabled' => true,
                'title' => '应用市场',
                'icon' => [
                    'light' => '<i class="icon-market"></i>',
                    'dark' => '<i class="icon-market"></i>',
                    'active' => '<i class="icon-market-fill"></i>'
                ],
                'url' => '/app/ai/market',
                'mobile' => true,
                'keep' => true
            ],
            'gallery' => [
                'enabled' => $enabledModelTypes['midjourney'] ?? false,
                'title' => '图片广场',
                'icon' => [
                    'light' => '<i class="icon-gallery"></i>',
                    'dark' => '<i class="icon-gallery"></i>',
                    'active' => '<i class="icon-gallery-fill"></i>'
                ],
                'url' => '/app/ai/gallery',
                'mobile' => true,
                'keep' => true
            ],
            'vip' => [
                'enabled' => $setting['enable_payment']??false,
                'title' => '会员充值',
                'icon' => [
                    'light' => '<i class="icon-vip"></i>',
                    'dark' => '<i class="icon-vip"></i>',
                    'active' => '<i class="icon-vip-fill"></i>'
                ],
                'url' => '/app/ai/user/vip',
                'mobile' => !($enabledModelTypes['midjourney'] ?? false),
            ],
            'me' => [
                'enabled' => true,
                'title' => '我的信息',
                'icon' => [
                    'light' => '<i class="icon-me"></i>',
                    'dark' => '<i class="icon-me"></i>',
                    'active' => '<i class="icon-me-fill"></i>'
                ],
                'url' => '/app/ai/user',
                'mobile' => true,
            ],
        ];
        $userId = session('user.id', session('user.uid'));
        if (config('plugin.ai.env.hide_midjourney') && (!$userId || User::getBalance($userId, 'midjourney') <= 0)) {
            unset($menus['painting']);
            unset($menus['gallery']);
        }
        $eventData = new EventData($menus);
        Event::dispatch('ai.menu.list', $eventData);
        return $this->json(0, 'ok', [
            'version' => config('plugin.ai.app.version'),
            'defaultModels' => $models,
            'enabledAlipay' => static::alipayEnabled(),
            'enabledWechat' => static::wechatEnabled(),
            'enablePayment' => $setting['enable_payment']??false,
            'icp' => $setting['icp']??'',
            'beian' => $setting['beian']??'',
            'footer_txt' => $setting['footer_txt']??'',
            'enabledModelTypes' => $enabledModelTypes,
            'plans' => Plan::getSetting(),
            'audio' => [
                'enable_xunfei_iat' => (bool)($audioSetting['enable_xunfei_iat'] ?? false),
                'enable_yingying_tts' => (Common::getModelInfoByType('ying')->status ?? 1) === 0,
                'enable_gpt_tts' => (Common::getModelInfoByType('tts')->status ?? 1) === 0
            ],
            'menus' => $eventData->data,
        ]);
    }

    /**
     * 可用模型
     *
     * @param Request $request
     * @return Response
     */
    public function models(Request $request): Response
    {
        $models = [];
        foreach (Model::getSetting() as $model => $name) {
            $models[] = [
                'name' => $name,
                'value' => $model
            ];
        }
        return $this->json(0, 'ok', $models);
    }


    /**
     * 获取所有分类
     *
     * @param Request $request
     * @return Response
     */
    public function categories(Request $request): Response
    {
        $categories = explode("\n", Category::getSetting());
        $categories = array_filter($categories, 'strlen');
        $data = [];
        foreach ($categories as $category) {
            $category = trim($category);
            if ($category === '') continue;
            $data[] = [
                'name' => $category,
                'value' => $category
            ];
        }
        return json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
    }

}
